import os
import io
import re
import sys
import csv
import json
import time
import base64
import winreg
import random
import zipfile
import pathlib
import shutil
import tkinter
import logging
import ddddocr
import easydict
import requests
import selenium
import importlib
import threading
import webbrowser
import subprocess
import tkinter.ttk
from PIL import Image
from aip import AipOcr
import tkinter.messagebox
import tkinter.scrolledtext
import selenium.webdriver.common
import selenium.common.exceptions
from selenium.webdriver.support import expected_conditions
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart


USER_AGENT = [
	"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)",
	"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
	"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
	"Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
	"Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
	"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
	"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
	"Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
	"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
	"Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
	"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
	"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
	"Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
	"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
	"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
	"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
	"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52"
]

HEADERS = {
    'User-Agent': random.choice(USER_AGENT),  # 浏览器头部
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Connection': 'keep-alive',
}


def print_log(log):
    """打印日志"""
    log_path = pathlib.Path("main_log")
    log_path.mkdir(exist_ok=True)
    time_now = time.localtime(time.time())
    timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time_now)

    log = f"{timestamp}  {log}\n"
    log_file = log_path / time.strftime(f"log-%Y-%m-%d.txt", time_now)
    with open(log_file, "a+", encoding="utf-8") as f:
        f.write(log)
    print(log, end="")


def get_gitee_json(url: str, timeout=10):
    try:
        res = requests.get(url, headers=HEADERS, timeout=timeout)
        if res.text == '':
            url = url.replace("config/", "config/backup/").split(".json")[0]
            return get_gitee_json(url)
        return res.text
    except:
        return None


def download_update(update_url):
    # update_url = "https://gitee.com/MemoryD/TaobaoCheck/raw/master/taobao_check.zip"
    file = requests.get(update_url, headers=HEADERS)
    if file.status_code != 200:
        return

    with open("taobao_check.zip", 'wb') as zip_file:  # 保存文件到脚本所在目录
        zip_file.write(file.content)

    f = zipfile.ZipFile("taobao_check.zip", 'r')
    for file in f.namelist():
        f.extract(file)

    return True


def delete_py():
    pack = pathlib.Path("taobao_check").absolute()
    print_log(f"taobao_check: {pack}")
    if pack != pathlib.Path("C:\\TaobaoCheck\\taobao_check"):
        return
    for i in pack.rglob("*.py"):
        os.remove(i)
    for i in pack.rglob("__pycache__"):
        shutil.rmtree(i, ignore_errors=True)


def run_async(func):
    """让函数异步执行的装饰器"""
    def wrapper(*args, **kwargs):
        thr = threading.Thread(target=func, args=args, kwargs=kwargs)
        thr.setDaemon(True)
        thr.start()

    return wrapper


class StartUI(tkinter.Tk):
    def __init__(self, version):
        super().__init__()
        self.title("自动更新")
        self.maxsize(400, 250)
        self.minsize(300, 200)
        self.log_text = tkinter.StringVar()
        self.log_text.set("自动更新")
        self.set_ui()
        self.center_window()
        self.check_update(version)

    def set_ui(self):
        self.progressbar = tkinter.ttk.Progressbar(self, length=250, mode='indeterminate', orient=tkinter.HORIZONTAL)
        self.progressbar.pack(pady=30)
        self.progressbar.start(10)

        self.log = tkinter.ttk.Label(textvariable=self.log_text, font=("微软雅黑", 10), foreground="green")
        self.log.pack(pady=30)

    @run_async
    def check_update(self, version):
        self.check(version)
        delete_py()
        self.destroy()

    def check(self, version):
        self.print_log(f"当前版本: V{version}")
        self.print_log("获取更新信息...")
        config = get_gitee_json("https://gitee.com/MemoryD/TaobaoCheck/raw/master/config/update.json")
        if not config:
            self.print_log("获取失败.")
            return
        time.sleep(0.5)
        self.print_log("获取成功.")
        config = json.loads(config)
        latest_version = config["latest_version"]
        self.print_log(f"最新版本: V{latest_version}")
        if latest_version <= version:
            self.print_log("已是更新版本.")
            time.sleep(0.5)
            return
        if version != "0.0.0":
            if version < config["min_base"]:
                tkinter.messagebox.showinfo("更新", "最新版本需要手动下载安装包更新。")
                return
        self.print_log("下载最新版本...")
        try:
            download_update(config["update_url"])
            self.print_log("下载成功.")
        except:
            self.print_log("下载失败.")

        self.print_log("更新成功，启动软件!")
        time.sleep(0.5)

    def print_log(self, text):
        print_log(text)
        self.log_text.set(text)

    def center_window(self):
        """窗口居中"""
        self.update()
        screenwidth = self.winfo_screenwidth()
        screenheight = self.winfo_screenheight()
        width = self.winfo_width()
        height = self.winfo_height()
        size = '+%d+%d' % ((screenwidth - width)/2, (screenheight - height)/2-50)
        self.geometry(size)
        self.resizable(False, False)


def product_first(version):
    print_log("第一次启动，检查更新")
    start = StartUI(version)
    start.mainloop()
    my_pid = os.getpid()
    cmd = f"{sys.executable} {os.path.abspath(__file__)} {my_pid}"
    subprocess.run(cmd, shell=False)


if __name__ == "__main__":
    print_log("启动程序.")
    currnet_path = pathlib.Path().absolute()
    print_log(f"当前路径: {currnet_path}")
    delete_py()
    try:
        taobao = importlib.import_module("taobao_check")
    except ModuleNotFoundError:
        print_log("无法导入taobao_check")
        if currnet_path == pathlib.Path("C:\\TaobaoCheck"):
            product_first("0.0.0")
    else:
        # 判断是生产环境还是开发环境，开发环境无需更新
        if currnet_path == pathlib.Path("C:\\TaobaoCheck"):
            print_log("当前环境：生产环境")
            if len(sys.argv) == 1:
                product_first(taobao.version)
            else:
                print_log("更新之后启动")
                print_log(f"pid: {sys.argv[-1]}")
                taobao.run(int(sys.argv[-1]))
        else:
            print_log("当前环境：开发环境")
            taobao.run()
